<template>
  <div class="user-management">
    <el-card>
      <div slot="header" class="page-header">
        <h2>用户管理</h2>
        <div class="header-actions">
          <el-input
              v-model="searchQuery"
              placeholder="搜索用户名或姓名"
              clearable
              style="width: 200px; margin-right: 10px;"
              @clear="handleSearch"
              @keyup.enter.native="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加用户
          </el-button>
          <el-button
              type="danger" @click="deleteMore"
              :disabled="idArr.length === 0">
<!--            idArr 是在 handleSelectionChange 方法中维护的数组，存储了所有被选中行的 id。
            当没有勾选任何复选框时，idArr 为空（length === 0），disabled 为 true，按钮禁用（灰色不可点击）。
            当勾选至少一个复选框时，idArr 有元素（length > 0），disabled 为 false，按钮启用（可点击）。-->
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
          <el-button type="warning" @click="handleLogout">
            <i class="el-icon-switch-button"></i> 退出登录
          </el-button>
        </div>
      </div>
      <div>
        <el-table
            :data="users"
            border
            stripe
            :loading="loading"
            style="width: 100%; margin-top: 10px;"
            @selection-change="handleSelectionChange"
        >
          <!-- 多选框 -->
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="id" label="序号" width="80"></el-table-column>
          <el-table-column prop="username" label="用户名" width="150"></el-table-column>
          <el-table-column prop="password" label="密码" width="150"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
          <el-table-column prop="money" label="余额" width="150"></el-table-column>
          <el-table-column prop="sex" label="性别" width="150">
            <template slot-scope="scope">
              <el-tag
                  :type="scope.row.sex == '1' ? 'primary' : 'success'"
                  disable-transitions>{{ scope.row.sex == '1' ? '男' : '女' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              prop="createTime"
              label="创建时间"
              width="180"
              :formatter="formatDate"
          ></el-table-column>

          <!-- 优化后的角色列 -->
          <el-table-column label="角色" width="200">
            <template slot-scope="scope">
              <!-- 有角色时显示标签 -->
              <template v-if="scope.row.roles && scope.row.roles.length > 0">
                <el-tag
                    v-for="(role, index) in scope.row.roles"
                    :key="role.id"
                    type="info"
                    size="mid"
                    style="margin-right: 5px;"
                >
                  {{ role.roleName }}
                </el-tag>
              </template>

              <!-- 无角色时：用灰色标签显示，与有角色样式统一 -->
              <!-- 保持相同大小 -->
              <!-- 略淡一点区分状态 -->
              <el-tag
                  v-else
                  type="default"
              size="mini"
              style="opacity: 1;"
              >
              暂无角色  <!-- 文案更柔和 -->
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>


      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="500px"
        :close-on-click-modal="false"


    >
      <el-form
          :model="form"
          :rules="rules"
          ref="userForm"
          label-width="100px"
          size="medium"
      >
      <!-- 用户名：中等宽度 -->
      <el-form-item label="用户名" prop="username">
        <el-input
            v-model="form.username"
            style="width: 300px;"
        ></el-input>
      </el-form-item>

      <!-- 密码：与用户名保持一致 -->
      <el-form-item label="密码" prop="password">
        <el-input
            v-model="form.password"
            style="width: 300px;"
        ></el-input>
      </el-form-item>

      <!-- 手机号：稍宽一些（适合11位数字） -->
      <el-form-item label="手机号" prop="phone">
        <el-input
            v-model="form.phone"
            style="width: 300px;"
        ></el-input>
      </el-form-item>

      <!-- 角色选择器：适应多选标签显示 -->
      <el-form-item label="角色" prop="roles">
        <el-select
            v-model="form.roles"
            placeholder="请选择角色"
            multiple
            collapse-tags
        style="width: 300px;"
        >
        <el-option
            v-for="role in roles"
            :key="role.id"
            :label="role.roleName"
            :value="role.id"
        ></el-option>
        </el-select>
      </el-form-item>

      <!-- 创建时间：与手机号宽度一致 -->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
            v-model="form.createTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 300px;"
        ></el-date-picker>
      </el-form-item>

      <!-- 余额：中等宽度 -->
      <el-form-item label="余额" prop="money">
        <el-input
            v-model="form.money"
            style="width: 300px;"
        ></el-input>
      </el-form-item>

      <!-- 性别：紧凑布局 -->
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="form.sex" style="width: 300px;">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>


import axios from "axios";

export default {
  name: 'UserManagement',
  data() {
    return {
      idArr: [],
      users: [],
      rolesList:[],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      loading: false,
      searchQuery: '',
      username: '',
      dialogVisible: false,
      dialogTitle: '添加用户',
      form: {
        id: '',
        username: '',
        password: '',
        phone: '',
        createTime: '',
        money: '',
        sex: '',
        roles: '',
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ],
        money: [
          {required: true, message: '请输入余额', trigger: 'blur'},
        ],
        phone: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请输入性别', trigger: 'blur'}
        ],
        createTime: [
          {required: true, message: '请选择日期', trigger: 'blur'}
        ]
      },
// 表单中可选择的所有角色
      roles: [
        { "id": 1, "roleName": "超级管理员" },
        { "id": 2, "roleName": "员工" },
        { "id": 3, "roleName": "部门经理" }
      ]

    }
  },
  computed: {},
  methods: {
    // 获取用户列表
    async getUserList() {
      this.loading = true;
      try {
        // 使用axios直接发起GET请求
        const response = await axios.get(
            // 拼接基础API地址和接口路径
            "http://localhost:10001/user/list",
            {
              // URL查询参数
              params: {
                username: this.searchQuery,
                pageNum: this.currentPage,
                pageSize: this.pageSize,

              },
            }
        );

        // 假设后端返回格式：{ code: 2000, data: { list: [], total: 0 } }
        if (response.data.code === 2000) {

          this.users = response.data.data.list;
          this.total = response.data.data.total;

        } else {
          // 处理后端返回的业务错误
          this.$message.error(response.data.message || '获取用户列表失败');
        }
      } catch (error) {
        // 处理网络错误或服务器异常
        if (error.response) {
          // 服务器返回错误状态码（如401、500等）
          this.$message.error(`获取失败 (${error.response.status})：${error.response.data?.message || '服务器错误'}`);
        } else if (error.request) {
          // 请求已发出但无响应
          this.$message.error('网络异常，无法连接服务器');
        } else {
          // 其他错误
          this.$message.error('获取用户列表失败：' + error.message);
        }
        console.error('获取用户列表错误：', error);
      } finally {
        this.loading = false;
      }
    },



    // 格式化日期显示
    formatDate(row) {
      return row.createTime
    },

    // 搜索用户
    handleSearch() {
      this.currentPage = 1
      this.username = this.searchQuery
      this.getUserList()
    },

    // 处理添加用户
    handleAdd() {
      this.dialogTitle = '添加用户'
      this.form = {
        id: null,
        username: '',
        password: '',
        phone: '',
        money: '',
        createTime: '',
        sex: '',
        roles: ''
      }
      this.dialogVisible = true
    },

    // 处理编辑用户
    handleEdit(row) {
      this.dialogTitle = '编辑用户'
      this.form = {...row}
      // 3. 关键：提取角色的 id 组成数组，赋值给 form.roles
      //    row.roles 是用户已有角色数组（格式：[{id:2, roleName:'员工'}, ...]）
      this.form.roles = row.roles.map(role => role.id);
      this.dialogVisible = true
    },

    // 处理删除用户
    async handleDelete(id) {
      try {
        await this.$confirm('确定要删除序号为' + id + '的用户吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        console.log(id)
        await axios.get(
            `http://localhost:10001/user/delete/${id}`,
        )
        this.$message.success('删除成功')
        await this.getUserList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
          console.error(error)
        }
      }
    },

    //批量选择处理,将选择的数据的id装入iaArr
    handleSelectionChange(val) {
      // val是table组件中触发复习框数据,自动传递过来被选择的行数据对象
      // console.log("复选框改变,val",val)
      // 遍历val,获取所有的id
      //console.log(val)
      this.idArr = [];
      val.forEach(item => {
        this.idArr.push(item.id);
      });
      console.log(this.idArr)
    },
    async deleteMore() {
      await this.$confirm('确定要删除序号为' + this.idArr + '的用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
           axios.post(
              'http://localhost:10001/user/delete/all', this.idArr).then(response => {
                if (response.data.code === 2000) {
                this.$message.success('删除成功')
                this.getUserList()
                }
          }).catch(error => {
            this.$message.error('删除失败')
            console.error(error)
          }
      ).catch(error => {
        if (error !== 'cancel') {
          this.$message.info('已取消')
        }

      })


    },


    // 提交表单
    async handleSubmit() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.form.id) {
              // 编辑操作
              //await updateUser(this.form)
              await axios.post(
                  'http://localhost:10001/user/update',
                  this.form
              ).then(response => {
                if (response.data.code === 2000) {
                  this.$message.success('更新成功')
                }
              })

            } else {
              // 添加操作
              await  axios.post(
                  'http://localhost:10001/user/add',
                  this.form
              ).then(response => {
                if (response.data.code === 2000) {
                  this.$message.success('添加成功')
                }
              })
            }
            this.dialogVisible = false
            await this.getUserList()
          } catch (error) {
            this.$message.error(this.form.id ? '更新失败' : '添加失败')
            console.error(error)
          }
        }
      })
    },

    // 处理分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.getUserList()
    },

    // 处理当前页变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUserList()
    },

    // 退出登录
    handleLogout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        axios.post("http://localhost:10001/user/logout",{
          token:this.$store.state.token
        }).then(response => {
          if (response.data.code === 2000) {
            this.$store.commit('setToken','')
            console.log("退出登录后token：",this.$store.state.token);
            this.$router.push('/login')
            this.$message.success('已退出登录')
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {
        // 取消退出
      })
    }
  },
  mounted() {
    this.getUserList()
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}


</style>
